package com.ljl.system.service.impl;

import com.ljl.system.domain.Menu;
import com.ljl.system.mapper.MenuMapper;
import com.ljl.system.service.IMenuService;
import com.ljl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> menuTree() {

        List<Menu> menus = menuMapper.findAll();

        HashMap<Long, Menu> menuMap = new HashMap<>();

        for (Menu menu : menus) {
            menuMap.put(menu.getId(),menu);
        }

        ArrayList<Menu> menuTree = new ArrayList<>();

        for (Menu menu : menus) {
            if (menu.getParent_id() == null){
                menuTree.add(menu);

            } else {
                Long parent_id = menu.getParent_id();
                Menu parent = menuMap.get(parent_id);
                parent.getChildren().add(menu);
            }

        }
        return menuTree;
    }
}
